package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.SignInDetailsActivity;
import com.mingtu.jgspatrol.adapter.MySignInRecordAdapter;
import com.mingtu.jgspatrol.base.Application;
import com.mingtu.jgspatrol.bean.AllSignInRecordBean;
import com.mingtu.jgspatrol.databinding.FragmentMySignInRecordBinding;
import com.mingtu.jgspatrol.room.SignInEvent;
import com.mingtu.jgspatrol.room.SignInEventDao;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MySignInRecordFragment extends BaseBindingFragment<FragmentMySignInRecordBinding> implements LazyFragmentPagerAdapter.Laziable {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private MySignInRecordAdapter mySignInRecordAdapter;
    private List<SignInEvent> signInEventList;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String beginTime = null;
    private String endTime = null;

    public static MySignInRecordFragment getInstance() {
        MySignInRecordFragment fragment = new MySignInRecordFragment();
        return fragment;
    }

    public static MySignInRecordFragment getInstance(String beginTime, String endTime) {
        MySignInRecordFragment fragment = new MySignInRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, beginTime);
        bundle.putString(ARG_PARAM2, endTime);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            beginTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_sign_in_record;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);

        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        mySignInRecordAdapter = new MySignInRecordAdapter(context);
        if (isOpenLoadAnimation) {
            mySignInRecordAdapter.isFirstOnly(isFirstOnly);
            mySignInRecordAdapter.openLoadAnimation(animationType);
        }

        mySignInRecordAdapter.setEmptyView(new EmptyDataLayout(context));
        View footerView = View.inflate(getActivity(), R.layout.layout_bio_bottom_place, null);
        mySignInRecordAdapter.addFooterView(footerView);

        binding.recycler.setAdapter(mySignInRecordAdapter);
        mySignInRecordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<AllSignInRecordBean.PageBean.ListBean> listBeans = mySignInRecordAdapter.getData();
                AllSignInRecordBean.PageBean.ListBean listBean = listBeans.get(position);
                boolean isUpload = listBean.isUpload();
                //Object implements Serializable或者继承Parcelable,list必须是ArrayList（若是List会提示错误）
                if (isUpload) {
                    ArrayList<Object> list = new ArrayList<Object>();
                    list.add(listBean);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("object", (Serializable) list);
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), SignInDetailsActivity.class, bundle);
                } else {
                    ToastUtils.showLong("离线的记录暂不能查看详情哦~");
                }
            }
        });


    }

    @Override
    protected void initView() {
     
    }

    @Override
    protected void getData() {
        initListener();
        getSignInRecordList(1);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //当用户处在次页面的时候，联网之后刷新数据
        String message = event.getMessgae();
        if (message.equals(MyConstant.getInstance().REFRESH_MY_SIGN_IN_DATA)) {
            getSignInRecordList(1);
        }

    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getSignInRecordList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(mySignInRecordAdapter.getData(), Constant.PAGE_SIZE);
                    getSignInRecordList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 动物资源列表
     *
     * @param pageNum
     */
    private void getSignInRecordList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_MY_SIGN_IN_RECORD)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            Gson gson = GsonFactory.getSingletonGson();
                            AllSignInRecordBean allReportRecord = new AllSignInRecordBean();
                            allReportRecord = gson.fromJson(result, AllSignInRecordBean.class);

                            AllSignInRecordBean.PageBean pageBean = allReportRecord.getPage();
                            List<AllSignInRecordBean.PageBean.ListBean> listBeans = pageBean.getList();
                            try {
                                if (listBeans != null) {
                                    isLoadMore = listBeans.size() > 0 && listBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;

                                    //设置为已经上报
                                    for (int i = 0; i < listBeans.size(); i++) {
                                        AllSignInRecordBean.PageBean.ListBean listBean = listBeans.get(i);
                                        listBean.setUpload(true);
                                    }

                                    //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                    if (currentPage == 1) {
                                        mySignInRecordAdapter.replaceData(listBeans);
                                    } else {
                                        mySignInRecordAdapter.addData(listBeans);
                                    }
                                    noUploadData();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        noUploadData();
                    }
                });
    }


    /**
     * 未上传的数据
     */
    private void noUploadData() {
        //未上传的数据
        List<AllSignInRecordBean.PageBean.ListBean> dataBeans = new ArrayList<>();
        SignInEventDao signInEventDao = Application.getApplication().getSignInEventDao();
        signInEventList = signInEventDao.getAll();
        for (int i = 0; i < signInEventList.size(); i++) {
            SignInEvent signInEvent = signInEventList.get(i);
            String clockTime = signInEvent.getClockTime();
            String content = signInEvent.getContent();
            String lat = signInEvent.getLat();
            String lng = signInEvent.getLng();


            AllSignInRecordBean.PageBean.ListBean listBean = new AllSignInRecordBean.PageBean.ListBean();
            listBean.setUpload(false);
            listBean.setClockTime(clockTime);
            listBean.setContent(content);
            listBean.setLnglat(lng + "," + lat);

            List<AllSignInRecordBean.PageBean.ListBean.TaskClockAttachEntityListBean> taskClockAttachEntityList = new ArrayList<>();
            List<SignInEvent.MyattachVOSBean> myattachVOSBeans = signInEvent.getMyattachVOS();
            for (int j = 0; j < myattachVOSBeans.size(); j++) {
                SignInEvent.MyattachVOSBean myattachVOSBean = myattachVOSBeans.get(j);
                String pathName = myattachVOSBean.getPathName();
                AllSignInRecordBean.PageBean.ListBean.TaskClockAttachEntityListBean entityListBean = new AllSignInRecordBean.PageBean.ListBean.TaskClockAttachEntityListBean();
                entityListBean.setUrl(pathName);
                taskClockAttachEntityList.add(entityListBean);
            }

            listBean.setTaskClockAttachEntityList(taskClockAttachEntityList);
            dataBeans.add(listBean);
        }
        if (dataBeans.size() > 0) {
            mySignInRecordAdapter.addData(0, dataBeans);
        }
    }


}